#ifndef READ_AND_WRITE_HPP
#define READ_AND_WRITE_HPP

#include "filesystem"
#include "iostream"
#include "nlohmann/json.hpp"
#include <fstream>

inline nlohmann::json read_from_file(const std::string &filename,
                                     nlohmann::json &json) {
  std::string full_path;

  // 检查是否是绝对路径
  if (filename.size() > 0 && filename[0] == '/') {
    full_path = filename; // 已经是绝对路径
  } else {
    // 使用相对路径
    std::string root_path =
        std::filesystem::current_path().parent_path().string();
    full_path = root_path + "/" + filename;
  }

  // 检查文件是否存在
  if (!std::filesystem::exists(full_path)) {
    std::cerr << "文件不存在: " << full_path << std::endl;
    // 如果文件不存在，创建一个空的JSON对象
    json = nlohmann::json::object();
    return json;
  }

  std::ifstream f(full_path);
  if (!f.good()) {
    std::cerr << "无法打开文件: " << full_path << std::endl;
    // 如果文件无法打开，创建一个空的JSON对象
    json = nlohmann::json::object();
    return json;
  }

  try {
    // 检查文件是否为空
    f.seekg(0, std::ios::end);
    size_t size = f.tellg();
    if (size == 0) {
      std::cerr << "文件为空: " << full_path << std::endl;
      // 如果文件为空，创建一个空的JSON对象
      json = nlohmann::json::object();
    } else {
      f.seekg(0, std::ios::beg);
      json = nlohmann::json::parse(f);
    }
  } catch (const std::exception &e) {
    std::cerr << "解析JSON文件时出错: " << e.what() << std::endl;
    // 解析出错，创建一个空的JSON对象
    json = nlohmann::json::object();
  }

  f.close();
  return json;
}

inline void write_to_file(const std::string &filename,
                          const nlohmann::json &json) {
  std::string full_path;

  // 检查是否是绝对路径
  if (filename.size() > 0 && filename[0] == '/') {
    full_path = filename; // 已经是绝对路径
  } else {
    // 使用相对路径
    std::string root_path =
        std::filesystem::current_path().parent_path().string();
    full_path = root_path + "/" + filename;
  }

  // 确保目录存在
  std::string directory = full_path.substr(0, full_path.find_last_of("/\\"));
  std::filesystem::create_directories(directory);

  std::ofstream f(full_path);
  if (!f.good()) {
    std::cerr << "无法写入文件: " << full_path << std::endl;
    return;
  }

  f << json.dump(4);
  f.close();
  std::cout << "成功保存到: " << full_path << std::endl;
}
inline void new_file(const std::string &filename, const nlohmann::json &json) {
  std::string full_path;

  // 检查是否是绝对路径
  if (filename.size() > 0 && filename[0] == '/') {
    full_path = filename; // 已经是绝对路径
  } else {
    // 使用相对路径
    std::string root_path =
        std::filesystem::current_path().parent_path().string();
    full_path = root_path + "/" + filename;
  }

  // 确保目录存在
  std::string directory = full_path.substr(0, full_path.find_last_of("/\\"));
  std::filesystem::create_directories(directory);

  std::ofstream f(full_path);

  f << json.dump(4);
  f.close();
  std::cout << "new file " << full_path << " success" << std::endl;
}
#endif // READ_AND_WRITE_HPP